package com.costeaalex.datedrivenfilecopy.model;

/**
 * @author Alex Costea
 * 
 * Copier model encapsulates the recursive business logic to copy previous files using an ICopier.
 * 
 */

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Observable;

import com.costeaalex.datedrivenfilecopy.model.interfaces.ICopier;

public class CopyModel extends Observable implements Runnable
	{
	
	private File directory;
	private long timestamp;
	private String path;
	private ICopier iC;
	
	public CopyModel(String source, String destination, String startDate, ICopier iC) {
		this.directory=new File(source);
		this.path=destination;
		this.iC=iC;
		
		DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
		try {
			Date date = dateFormat.parse(startDate);
			this.timestamp = date.getTime();
		}
		catch(Exception e) {
			e.printStackTrace();
			System.exit(0);
		}
	}
	
	public void run() {
		iC.init();
		copy(directory);
		iC.destroy();
		setChanged();
		notifyObservers("Done");
		}
		
	private void copy(File directory)
		{
		String[] files = directory.list();
		File tmp;
	
		for(int i=0; i<files.length; i++)
			{
			tmp=new File(directory.getAbsolutePath().replace("\\", "/")+"/"+files[i]);
			if(tmp.isDirectory())
				{
				iC.copyDirectory(this.path+this.directory.toPath().relativize(tmp.toPath()).toString().replace("\\", "/"));
				copy(tmp);
				}
			else
				{
				if(tmp.lastModified()>=timestamp) {
					iC.copyFile(tmp.toString(), (this.path+this.directory.toPath().relativize(tmp.toPath()).toString()).replace("\\", "/"));
					setChanged();
					notifyObservers(tmp.toPath());
				}
			}
		}
	}
}
